/*
 * @Description: 
 * @Author: hrc
 * @Date: 2024-12-16 14:29:47
 * @LastEditors: HuRrongChao
 * @LastEditTime: 2024-12-16 15:14:01
 */
import { onMounted, onBeforeUnmount, ref } from 'vue'

export function useContextMenu(containerRef) {
  const x = ref(0)
  const y = ref(0)
  const visible = ref(false)

  // 打开菜单
  const open = (e) => {
    e.preventDefault() //阻止默认行为
    e.stopPropagation() //阻止冒泡
    x.value = e.clientX
    y.value = e.clientY
    visible.value = true
  }

  // 关闭菜单
  const closeMenu = () => {
    visible.value = false
  }

  onMounted(() => {
    const dom = containerRef.value
    dom.addEventListener('contextmenu', open)
    window.addEventListener('click', closeMenu, true)
    window.addEventListener('contextmenu', closeMenu, true)
  })

  onBeforeUnmount(() => {
    const dom = containerRef.value
    dom.removeEventListener('contextmenu', open)
    window.removeEventListener('click', closeMenu, true)
    window.removeEventListener('contextmenu', closeMenu, true)
  })

  return {
    x,
    y,
    visible
  }
}